package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.Vo.UserVo;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @Author Justin Parker
 * @Date 2024/8/9 0009 18:36
 * @Version 1.0
 */
@RestController
@RequestMapping("/v1/user/")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @RequestMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println("userDTO = " + userRegDTO);
        String username = userRegDTO.getUsername();
        UserVo userVo = userMapper.selectByUsername(username);
        if (userVo != null){
            return 0; //用户名已存在
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return 1;
    }

    @RequestMapping("login")
    public int login(@RequestBody UserRegDTO userRegDTO, HttpSession session){
        System.out.println("userRegDTO = " + userRegDTO);
        String username = userRegDTO.getUsername();
        UserVo userVo = userMapper.selectByUsername(username);
        if (userVo == null){
            return 0;
        }
        if (userVo.getPassword().equals(userRegDTO.getPassword())){
            session.setAttribute("user",userVo);
            return 1;
        }
            return 2;
    }

    @RequestMapping("/current")
    public UserVo currentUser(HttpSession session){
        UserVo userVo =(UserVo) session.getAttribute("user");
        return userVo;
    }

    @RequestMapping("logout")
    public int logout(HttpSession session){
        session.removeAttribute("user");
        return 1;
    }
}
